<?php

class Menu
{

  protected $items = array();

  public function __construct($menu = null)
  {
    if (is_array($menu)) {
      $this->parse($menu, $this);
    }
  }

  public static function parse($items, $menu = null)
  {
    if (is_a($items, 'Menu')) {
      return $items;
    }

    if (! $menu) {
      $menu = new Menu();
    }

    foreach ($items as $name => $item) {
      if ($item instanceof MenuItem) {
        $menu->addItem($item);
      }
      else {
        $submenu = sy_get_param($item, 'submenu') ? Menu::parse(sy_get_param($item, 'submenu')) : null;

        $Item = new MenuItem($name, sy_get_param($item, 'label'), sy_get_param($item, 'url'), sy_get_param($item, 'regex'), $submenu);

        if (isset($item['item_index'])) {
          $menu->addItemAt($Item, $item['item_index']);
        } else {
          $menu->addItem($Item);
        }
      }
    }

    return $menu;
  }

  public function count()
  {
    return count($this->items);
  }

  public function addItem(MenuItem $item)
  {
    $this->items[] = $item;
  }

  public function addItemAt(MenuItem $item, $index)
  {
    array_splice($this->items, $index, 0, array($item));
  }

  public function getItemAt($index)
  {
    return $this->items[$index];
  }

  public function getItemByName($name)
  {
    $index = count($this->items) - 1;

    while ($index >= 0 && $this->items[$index]->name != $name)
      $index --;

    if ($index < 0) {
      throw new Exception("Menu item not found: <b>$name</b>");
    }

    return $this->items[$index];
  }

  public function getItemIndex(MenuItem $item)
  {
    $index = count($this->items) - 1;

    while ($index >= 0 && $this->items[$index]->name != $name)
      $index --;

    if ($index < 0) {
      throw new Exception("Menu item does not exist in menu");
    }

    return $index;
  }

}

?>